using UnityEngine;
using System.Collections;

public class CowboyEvent : MonoBehaviour {
	
	//-- properties --//
	
	// flags for running
	private const int maxAlive = 5;
	private const float spawnRate = 2.5f;
	private const float totalEncountTimer = 30f;
	
	private bool hasRun;
	private bool isRunning;
	private float runUntil;
	private float lastSpawnAt = 0;
	
	// spawns
	public GameObject cowboySpawnContainer;
	
	// gate to clear
	public GameObject rightHandBlockage;

	
	//-- methods --//
	// Use this for initialization
	void Start () {
		//...
	}
	
	// Update is called once per frame
	void Update () {
		if (hasRun || !isRunning) {
			return;
		}
		
		// still spawning?
		float now = Time.timeSinceLevelLoad;
		if (now < runUntil) {
			// clear up dead things
			int runningCowboys = 0;
			ArrayList emptyTransforms = new ArrayList();
			
			foreach (Transform spawnObj in cowboySpawnContainer.transform) {
				// check for any kids
				if (spawnObj.childCount > 0)
					runningCowboys ++;
				else
					emptyTransforms.Add ( spawnObj );
			}
			
			// need more?
			if (runningCowboys < maxAlive) {
				
				// too soon?
				if (lastSpawnAt == 0 || (lastSpawnAt + spawnRate) < now) {
					// spawn!
					
					// pick an available vector
					int spawn = Random.Range( 0, emptyTransforms.Count );
					print (emptyTransforms.Count + " " + spawn );
					Transform spawnHere = (Transform) emptyTransforms[ spawn ];
					
					GameObject madeThis = (GameObject) GenerateObjects.cheatMakeEnemyOne( spawnHere.position );
					madeThis.transform.parent = spawnHere;
					
					// undo the last respawn addition
					GenerateObjects.originalLocations.RemoveAt( GenerateObjects.originalLocations.Count - 1 );
					GenerateObjects.originalTags.RemoveAt( GenerateObjects.originalTags.Count - 1 );
					GenerateObjects.everyEnemy.RemoveAt( GenerateObjects.everyEnemy.Count - 1 );
				}
			}
		}
		else {
			// we're done!
			hasRun = true;
			
			// do something better?
			// TODO particle?
			Destroy( rightHandBlockage );
		}
	}
	
	// start it up?
	void OnTriggerEnter (Collider other) {
		if (hasRun || isRunning)
			return;
		
		if (other.gameObject.CompareTag( "Player" )) {

			// TODO notification on start
			
			float now = Time.timeSinceLevelLoad;
			runUntil = Time.timeSinceLevelLoad + totalEncountTimer;
			lastSpawnAt = now;
			isRunning = true;
		}
	}
}
